<template>
    <div>
        <div style="height: 50px;background-color: #3763A6">
            <img src="../../assets/img/deployment/dutyDevelopTitle.png" class="" style="height: 100%" alt="">
        </div>

        <div class="d-flex">

            <div class="w-100 d-flex flex-column">
                <div class="p-6 flex-no-zoom">
                    <DeploymentSearch @noSearchForm="noSearchForm" @getSquadrons="getSquadrons"
                                      @exportExcel="exportExcel"></DeploymentSearch>
                </div>

                <div class="d-flex mx-6 mb-6 h-100">
                    <div class="partBgBox mr-6 flex-no-zoom py-6 px-10 " style="width:340px;">
                        <div class="flexCenter">
                            <div class="titleBefore"></div>
                            <div>岗位部署</div>
                        </div>

                        <div class="mt-6">
                            <a-table customRow :columns="emergencyDutySurveyColumns"
                                     :customRow="rowClick"
                                     :rowClassName="rowClassName"
                                     :data-source="emergencyDutySurveyList"
                                     size="small" :pagination="false" :scroll="{y:ws.wh-414-242}"
                                     rowKey="id"></a-table>
                            <div class="text-center mt-10">
                                <a-button type="primary" size="small" @click="submitPostion">
                                    提交
                                </a-button>
                            </div>
                        </div>
                    </div>

                    <div class="partBgBox w-100 py-6 px-10">
                        <div class="flexCenterBetween">
                            <div>
                                <a-button type="primary" size="small" class="mr-14" @click="newDuty"  v-if="canDeploy()">
                                    <a-icon type="plus"/>
                                    新增岗位
                                </a-button>
                                <a-button size="small" type="primary" @click="copyPostDeployBtn">
                                    <a-icon type="snippets"/>
                                    复用历史布岗
                                </a-button>
                            </div>


                            <div>
                                <a-radio-group v-model="addDutyFrom" :options="addDutyFromList"/>
                                <a-popconfirm title="确认复用当前档位?" ok-text="确定" cancel-text="取消"
                                              @confirm="copyPostDeploySave()" v-if="addDutyFrom!=2">

                                    <a-button type="primary" size="small">
                                        保存
                                    </a-button>
                                </a-popconfirm>
                                <a-button v-else type="primary" size="small" @click="copyPostDeploySave()">
                                    保存
                                </a-button>


                            </div>

                        </div>

                        <div class="mt-6">
                            <a-table :columns="emergencyDutyColumns" :data-source="emergencyDutyList" size="small"
                                     :pagination="false" rowKey="id">
                                    <span slot="action" slot-scope="text, record">
                                        <a href="#" @click="checkDetail(record)"><a-icon type="eye"
                                                                                         class="text-primary"/></a>
                                        <template v-if="canEdit(record)">
                                            <a-divider type="vertical"/>
                                            <a-popconfirm title="会清除当前岗位下的警察部署！确认修改?" ok-text="确定" cancel-text="取消"
                                                          :visible="record.EV"
                                                          @confirm="editItem(record)"
                                                          @visibleChange="editVisibleChange(record)">
                                        <a href="#"><a-icon type="edit" class="text-primary"/></a>
                                            </a-popconfirm>
                                        <a-divider type="vertical"/>
<!--                                             confirmTitle: "", //删除和修改校验师傅部警察-->
<!--                confirmVisible: false, //删除和修改校验师傅部警察-->
                                        <a-popconfirm :title="record.DT" ok-text="确定" cancel-text="取消"
                                                      :visible="record.DV"
                                                      @confirm="deleteItem(record)"
                                                      @visibleChange="deleteVisibleChange(record)">
                                            <a href="#"><a-icon type="delete" class="text-primary"/></a>
                                         </a-popconfirm>
                                        </template>

                                    </span>

                            </a-table>
                        </div>

                    </div>
                </div>
                <div class=" w-100 pb-6">
                    <div class="partBgBox mx-6  py-6 px-10">
                        <SecurityRiskAnalysis ref="securityRiskAnalysis" type="position"></SecurityRiskAnalysis>
                    </div>
                </div>
            </div>

            <DeploymentMap ref="deploymentMap" :searchParams="searchParams" :postInfor="postInforInMap" type="position"></DeploymentMap>
        </div>


        <!--新增和编辑-->
        <Jmodal :visible="crudModalVisible" :title="crudModalTitle" right="500" width="500" top="120"
                @cancel="crudModalVisible = false">
            <a-form-model
                    ref="ruleForm"
                    :model="requestBody"
                    :rules="rules"
                    :label-col="{ span: 5 }"
                    :wrapper-col="{ span: 19 }"
            >
                <a-form-model-item ref="positionType" label="岗位类型" prop="positionType">
                    <a-radio-group :options="dutyTypes" v-model="requestBody.positionType"
                                   @change="positionTypeChange()"/>
                </a-form-model-item>

                <a-form-model-item ref="deptId" label="所属大队" prop="deptId">
                    <a-select style="width: 259px" size="small" v-model="requestBody.deptId"
                              @change="brigadeChange()">
                        <a-select-option v-for="(item,i) in brigadeList" :key="i" :value="item.cdepartmentid">
                            {{item.cdepartmentname}}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>


                <a-form-model-item ref="middeptId" prop="middeptId" label="所属中队">
                    <a-select style="width: 259px" size="small" v-model="requestBody.middeptId"
                              @change="middeptIdChange($event)">
                        <a-select-option v-for="(item2,i2) in squadronList" :key="i2" :value="item2.cdepartmentid">
                            {{item2.deptshortname}}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>


                <a-form-model-item ref="name" label="岗位名称" prop="name" v-if="requestBody.positionType == 1">
                    <a-select style="width: 259px" size="small" v-model="requestBody.name">
                        <a-select-option v-for="(item,i) in postNameList" :key="i" :value="item.label">
                            {{item.label}}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>

                <a-form-model-item ref="lawEnforcement" label="执   法   站" prop="lawEnforcement"
                                   v-if="requestBody.positionType == 2">
                    <a-select style="width: 259px" size="small" v-model="requestBody.lawEnforcement" >
                        <a-select-option v-for="(item,i) in lawEnforcementStation" :key="i" :value="item.id">
                            {{item.name}}
                        </a-select-option>
                    </a-select>
                </a-form-model-item>


                <a-form-model-item ref="startTime" label="岗位时段" prop="startTime" required>
                    <div class="flexCenter mt-4">
                        <a-time-picker format="HH:mm" size="small" class="mr-4"
                                       v-model="requestBody.startTime"
                                       :minute-step="30"
                                       valueFormat="HH:mm"/>
                        <a-time-picker format="HH:mm" size="small" v-model="requestBody.endTime"
                                       :minute-step="30"
                                       valueFormat="HH:mm"/>
                    </div>
                </a-form-model-item>


                <template v-if="requestBody.positionType == 1">
                    <div class="border-top mt-14">
                        <div class="my-6">巡防岗：已选总长度 <span class="text-danger">{{requestBody.mileage}}</span>km</div>
                        <!--<div class="my-6" v-if="requestBody.positionType == 1">已选总长度：{{requestBody.mileage}}km</div>-->
                    </div>

                    <a-form-model-item class="my-6" ref="takes" label=""
                                       v-for="(item,i) in requestBody.takes" :key="i"
                                       :prop="'takes.' + i" required
                                       :rules="rules.takes"
                                       :label-col="{span:0}"
                                       :wrapper-col="{span:24}">

                        <div class="flexCenter">
                            <a-select style="width: 220px" size="small" v-model="item.motorwayId" @change="motorWayChange(item)" class="mr-4">
                                <a-select-option v-for="(item,i) in expresswayList" :key="i" :value="item.id">
                                    {{item.name}}
                                </a-select-option>
                            </a-select>
                            <a-input-number :max="item.max" :min="item.min" size="small" style="width: 80px"
                                            v-model="item.startStake"
                                            :formatter="value => `K${value}`" :parser="value => value.replace('K', '')">
                            </a-input-number>
                            <div class="mx-4"> -</div>

                            <a-input-number :max="item.max" :min="item.min" size="small" style="width: 80px"
                                            v-model="item.endStake"
                                            :formatter="value => `K${value}`" :parser="value => value.replace('K', '')">
                            </a-input-number>


                            <a-button type="primary" ghost class="px-4 ml-4" @click="addTakes(i)"
                                      size="small">
                                <a-icon type="plus"/>
                            </a-button>


                            <a-popconfirm title="确认删除?" ok-text="确定" cancel-text="取消"
                                          @confirm="minusTakes(i)" v-if="requestBody.takes.length>1">
                                <a-button type="danger" ghost class="px-4 ml-4"
                                          size="small">
                                    <a-icon type="minus"/>
                                </a-button>
                            </a-popconfirm>


                        </div>
                    </a-form-model-item>
                </template>


                <div class="mt-14 text-center">
                    <a-button size="small" class="mr-14" @click="crudModalVisible = false">
                        取消
                    </a-button>
                    <a-button type="primary" size="small" @click="onSubmit">
                        保存
                    </a-button>

                </div>

            </a-form-model>
        </Jmodal>


        <Jmodal :visible="copyPostModalVisible" title="岗位复用" right="100" width="400" top="120"
                @cancel="copyPostModalVisible = false">

            <div>
                <div class="mb-10">复用日期</div>
                <a-range-picker v-model="copyRange"/>
            </div>

            <div>
                <div class="my-10">目标日期</div>
                <a-range-picker v-model="targetRange"/>
            </div>

            <div class="mt-14 text-center">
                <a-button size="small" class="mr-14" @click="copyPostModalVisible = false">
                    取消
                </a-button>
                <a-button type="primary" size="small" @click="copyPostModalSubmit">
                    复用
                </a-button>

            </div>

        </Jmodal>

        <Jmodal :visible="postDetailModalVisible" title="岗位详情" right="100" width="400" top="120"
                @cancel="postDetailClose()">
            <div class="my-6">
                <span class="text-secondary">岗位名称:</span>
                <span> {{postInforInMap.name}}</span>
            </div>
            <div class="my-6">
                <span class="text-secondary">岗位类型:</span>
                <span>
                    {{postInforInMap.type|sysDic('dutyType')}}
                </span>
            </div>
            <div class="my-6">
                <span class="text-secondary">所属部门:</span>
                <span>
                    {{postInforInMap.deptName}}
                </span>
            </div>

            <div class="my-6">
                <span class="text-secondary">开始时间:</span>
                <span>
                    {{postInforInMap.startTime}}
                </span>
            </div>

            <div class="my-6">
                <span class="text-secondary">结束时间:</span>
                <span>
                    {{postInforInMap.endTime}}
                </span>
            </div>


        </Jmodal>


    </div>


</template>

<script>
    import DeploymentSearch from "@/components/deployment-search.vue";
    import SecurityRiskAnalysis from "@/components/deployment/security-risk-analysis.vue";
    import Jmodal from "@/components/jmodal.vue";
    import DeploymentMap from "@/components/deployment/deployment-map.vue";
    import {
        addPosition, copyPostDeploy,
        deletePosition, getbrigadeList,
        getEmergencyDutyList,exportEmergencyDutyList,
        getEmergencyDutySurveyList, getexpresswayList, getPositionDetail, getsquadronList,
        login, pileToCrd, submitPostion, updatePostion, getLawEnforcementStation, getLawRadius, getIsDeploy,saveDayPostion
    } from "../../common/api";
    import {sysDic} from "../../common/filters";
    import {sysDicRenderByType,s2ab,saveAs} from "../../utils/sys_utils";
    import store from "@/common/vuex";
    import * as moment from "moment";
    import * as XLSX from "xlsx-style";
    import {getDictsByType,getDictByTypeValue} from "../../utils/sys-dic-utils";
    import {getBetweenDates, isNullUndefined, jsonToExcel} from "../../utils/js-utils";
    import {postNameList} from "../../common/data/sys-data";

    export default {
        name: "post-deployment",
        components: {DeploymentSearch, SecurityRiskAnalysis, Jmodal, DeploymentMap},
        filters: {sysDic},
        data: function () {
            let timeRangeValidator = (rule, value, callback) => {
                if (!this.requestBody.startTime || !this.requestBody.endTime) {
                    callback(new Error('请选择开始结束时间'));
                } else {
                    callback();
                }
            };
            let takesValidator = (rule, value, callback) => {  //高速验证

                if (this.requestBody.positionType == 1) {
                    if (!value.motorwayId || isNullUndefined(value.startStake) || isNullUndefined(value.endStake)) {
                        callback(new Error('请正确填写岗位范围！'));
                    } else {
                        value.mileage = Math.abs(value.startStake - value.endStake);
                        this.requestBody.mileage = 0;
                        this.requestBody.takes.forEach(v => {
                            this.requestBody.mileage += v.mileage;
                        });
                        callback();
                    }
                } else {
                    callback();
                }

            };
            return {

                crudModalVisible: false,
                crudModalTitle: "",
                addDutyFrom: 0, //保存岗位类型
                addDutyFromList: [
                    {label: '全部复用', value: 0},
                    {label: '相同日期类型复用', value: 1},
                    {label: '不复用', value: 2},
                ],
                dutyTypes: getDictsByType('dutyType'),

                emergencyDutySurveyColumns: [
                    {
                        title: '已选日期',
                        dataIndex: 'positiondate',
                        key: 'positiondate',
                        align: 'center',
                        customRender: (v) => moment(v).format("YYYY-MM-DD")
                    }, {
                        title: '日期类型',
                        dataIndex: 'datetype',
                        key: 'datetype',
                        align: 'center',
                        customRender: sysDicRenderByType('dateType')
                    }, {
                        title: '状态',
                        dataIndex: 'substatus',
                        key: 'substatus',
                        align: 'center',
                        customRender: sysDicRenderByType('dutyStatus')
                    },
                ],

                emergencyDutyColumns: [
                    // {
                    //     title: '序号',
                    //     dataIndex: 'index',
                    //     key: 'index',
                    //     align: 'center',
                    //     customRender: (text, record, index) => {
                    //         return index + 1
                    //     }
                    // },
                    {
                        title: '岗位类型',
                        dataIndex: 'positiontype',
                        key: 'positiontype',
                        align: 'center',
                        customRender: sysDicRenderByType('dutyType')
                    }, {
                        title: '岗位名称',
                        dataIndex: 'fullName',
                        key: 'fullName',
                        align: 'center',
                    }, {
                        title: '所属部门',
                        dataIndex: 'middeptname',
                        key: 'middeptname',
                        align: 'center',
                    }, {
                        title: '岗位范围',
                        dataIndex: 'position',
                        key: 'position',
                        customRender: (text, record, index) => {
                            if (record.dutyRange2) {
                                return record.position + '-' + record.dutyRange2
                            } else {
                                return record.position;
                            }

                        }
                    }, {
                        title: '岗位时段',
                        dataIndex: 'starttime',
                        key: 'starttime',
                        customRender: (text, record, index) => {
                            return record.starttime + '-' + record.endtime
                        }
                    }, {
                        title: '操作',
                        dataIndex: 'action',
                        key: 'action',
                        scopedSlots: {customRender: 'action'},
                    },
                ],
                emergencyDutySurveyList: [], //部署列表
                emergencyDutyList: [], //部署详情列表


                selectedRow: {},  //岗位部署选中
                squadrons: [],//查询条件上的中队

                //添加 修改 查看
                searchParams: {}, //查询条件

                requestBody: defaultRequestBody(),
                brigadeList: [], // 大队
                squadronList: [], // 中队
                postNameList: postNameList, // 岗位名称
                lawEnforcementStation: [],  // 执法站
                expresswayList: [],  // 高速
                lawRadius: 500,  // 执法站半径

                rules: {
                    positionType: [
                        {required: true, message: '请选择岗位类型', trigger: 'change'},
                    ],
                    deptId: [
                        {required: true, message: '请选择大队', trigger: 'change'},
                    ],
                    middeptId: [
                        {required: true, message: '请选择中队', trigger: 'change'},
                    ],
                    name: [
                        {required: true, message: '请填写岗位名称', trigger: 'change'},
                    ],
                    lawEnforcement: [
                        {required: false, message: '请填写岗位名称', trigger: 'change'},
                    ],
                    startTime: [
                        {validator: timeRangeValidator, trigger: 'change'},
                    ],
                    takes: [
                        {
                            validator: takesValidator, trigger: 'change'
                        },
                    ],

                },
                // 详情
                postInforInMap: {}, //传给地图的岗位详情
                postDetailModalVisible: false,

                //历史复用
                copyPostModalVisible: false,
                copyRange: [],
                targetRange: [],


            }
        },
        computed: {
            ws() {
                return this.$store.state.ws
            },
            user() {
                return this.$store.state.user
            },

        },
        methods: {

            rowClick(record, index) {
                return {
                    on: {
                        click: () => {
                            this.selectedRow = record;
                            this.getEmergencyDutyList()
                        }
                    }
                };
            },
            //table行class
            rowClassName(record, index) {
                let className = "cursorPionter";
                if (record.id == this.selectedRow.id) {
                    className = "rowActive cursorPionter";
                    this.$emit('change', this.selectedRow)
                }
                return className;
            },
            getSquadrons(d) {
                this.squadrons = d;
            },
            noSearchForm(reqBody) {  //查询
                this.searchParams = reqBody;
                this.getEmergencyDutySurveyList(true);
            },

            getEmergencyDutySurveyList(init=false) { //岗位部署列表
                getEmergencyDutySurveyList(this.searchParams).then(res => {
                    if (res.isSuccess) {
                        this.emergencyDutySurveyList = res.data;
                        this.emergencyDutySurveyList.forEach((v, i) => {
                            v.index = i;
                        });
                        if(init){
                            this.selectedRow = this.emergencyDutySurveyList[0];
                            this.getEmergencyDutyList();
                        }

                    }
                })
            },
            getEmergencyDutyList() {  //岗位部署详情
                this.$message.loading({content: '数据加载中...', key: 'dutyLoadingKey', duration: 0});
                this.searchParams.currentTime = moment(this.selectedRow.positiondate).format('YYYY-MM-DD');
                getEmergencyDutyList(this.searchParams).then(res => {
                    if (res.isSuccess) {

                        this.$refs.securityRiskAnalysis.getCoverageRate(this.searchParams, this.selectedRow)
                        this.$refs.securityRiskAnalysis.getSecurityRiskAnalysisList(this.searchParams, this.selectedRow)

                        this.$message.success({content: '岗位部署详情加载成功!', key: 'dutyLoadingKey', duration: 2});
                        res.data.forEach(v => {
                            if (v.positiontype == 2) {
                                const n = v.name.split(',');
                                v.name = n[0];
                                v.id2 = n[1];
                            }
                            v.fullName = v.middeptname + "-" + v.name;
                            v.DV = false;
                            v.EV = false;
                            v.DT = "";
                        })
                        this.emergencyDutyList = res.data;
                    } else {
                        this.$message.error({
                            content: res.info ? res.info : '岗位部署详情加载失败!',
                            key: 'dutyLoadingKey',
                            duration: 2
                        });
                    }
                }, (e) => {
                    this.$message.error({
                        content: e.message ? e.message : '岗位部署详情加载失败!',
                        key: 'dutyLoadingKey',
                        duration: 2
                    });
                })
            },


            submitPostion() { //岗位提交
                var flag = true;
                var postData = [];
                this.emergencyDutySurveyList.forEach((v) => {
                    var item = {
                        deptId: this.searchParams.deptId,//大队id
                        // middeptId:'0002', //中队id
                        currentTime: moment(v.positiondate).format("YYYY-MM-DD") //当前时间对于那一天
                    };
                    postData.push(item);
                    if (v.substatus == 0) { //有未部署的；
                        flag = false;
                    }
                });
                if (!flag) {
                    this.$message.error("有大队未部岗！")
                    return;
                }
                this.$message.loading({content: '数据提交中...', key: 'loading1', duration: 0});
                submitPostion({params: postData}).then(res => {
                    if (res.isSuccess) {
                        this.$message.success({content: '数据提交成功!', key: 'loading1', duration: 2});
                        this.getEmergencyDutySurveyList();
                    } else {
                        this.$message.error({content: res.info ? res.info : '数据提交失败!', key: 'loading1', duration: 2});
                    }
                })
            },


            //新增岗位
            newDuty() {
                // console.log();
                this.crudModalVisible = true;
                this.crudModalTitle = "新增岗位";
                this.getbrigadeList();
                this.requestBody = defaultRequestBody();
                this.requestBody.deptId = this.searchParams.deptId;
                this.requestBody.middeptId = this.searchParams.middeptId;

            },
            motorWayChange(item) {
                console.log("高速变更！")
                this.expresswayList.forEach(v => {
                    if (item.motorwayId == v.id) {
                        item.max = v.endTake * 1;
                        item.min = v.startTake * 1;
                        item.startStake = v.startTake * 1;
                        item.endStake = v.endTake * 1;
                        item.mileage = Math.abs(item.startStake - item.endStake);
                    }

                    this.requestBody.mileage = 0;
                    this.requestBody.takes.forEach(v => {
                        this.requestBody.mileage += v.mileage;
                    });
                })

            },
            copyPostDeploySave() { //复制
                // {label: '全部复用', value: 0},
                // {label: '相同日期类型复用', value: 1},
                // {label: '不复用', value: 2},
                // selectedRow
                // 1	待提交
                // 2	已提交
                // 0	待部署
                // [{deptId,middeptId,motorwayId,times:"2010-09-01|2010-09-08,2010-09-03|2010-09-09"}]

                if (this.addDutyFrom == 2) {
                    const tempData = {
                        deptId: this.searchParams.deptId,
                        middeptId: this.searchParams.middeptId,
                        motorwayId: this.searchParams.motorwayId,
                        currentTime:this.selectedRow.positiondate};
                    this.$message.loading({content: '数据提交中...', key: 'loading1', duration: 0});
                    saveDayPostion(tempData).then(res=>{
                        if (res.isSuccess) {
                            this.$message.success({content: '保存成功!', key: 'loading1'});
                            this.getEmergencyDutySurveyList(); //刷新部署列表
                        } else {
                            this.$message.error({content: res.info ? res.info : '保存失败!', key: 'loading1'});
                        }
                    }, (e) => {
                        this.$message.error({content: e.message ? e.message : '保存失败!', key: 'loading1'});
                    })
                    this.$message.success("保存成功！");

                } else { //同中队未部署复用

                    const copyData = {
                        deptId: this.searchParams.deptId,
                        middeptId: this.searchParams.middeptId,
                        motorwayId: this.searchParams.motorwayId,};
                    const copyTime = moment(this.selectedRow.positiondate).format("YYYY-MM-DD");
                    copyData.currentTime = copyTime
                    const times = [];
                    this.emergencyDutySurveyList.forEach(v => {
                        if (v == this.selectedRow) { //非当条数据
                            return;
                        }
                        if (v.substatus == 0) { //未部署
                            if (this.addDutyFrom == 1 && v.datetype == this.selectedRow.datetype) { //同日期
                                times.push(copyTime + '|' + moment(v.positiondate).format("YYYY-MM-DD"))
                            } else {
                                times.push(copyTime + '|' + moment(v.positiondate).format("YYYY-MM-DD"))
                            }
                        }
                    })
                    if (times.length > 0) {
                        copyData.times = times.join(',');
                        this.$message.loading({content: '数据提交中...', key: 'loading1', duration: 0});
                        // console.log(copyData)
                        saveDayPostion(copyData).then(res => {
                            if (res.isSuccess) {
                                this.$message.success({content: '复制岗位成功!', key: 'loading1'});
                                this.getEmergencyDutySurveyList(); //刷新部署列表
                            } else {
                                this.$message.error({content: res.info ? res.info : '复制岗位失败!', key: 'loading1'});
                            }
                        }, (e) => {
                            this.$message.error({content: e.message ? e.message : '复制岗位失败!', key: 'loading1'});
                        })

                    } else {
                        this.$message.warn("没有找到复制目标！")
                    }

                }

            },
            copyPostDeployBtn() { //岗位历史复制
                this.copyPostModalVisible = true;
            },
            copyPostModalSubmit() {
                const copyDays = this.copyRange[1].diff(this.copyRange[0], 'days');
                const targetDays = this.targetRange[1].diff(this.targetRange[0], 'days');
                if (copyDays != targetDays) {
                    this.$message.warn("复制日期和目标日期天数不匹配！");
                    return;
                }
                const copyDates = getBetweenDates(...this.copyRange);
                const targetDates = getBetweenDates(...this.targetRange);
                let times = [];
                copyDates.forEach((v, i) => {
                    times.push(v + '|' + targetDates[i]);

                });
                const postBody = {deptId: this.searchParams.deptId, times: times.join(',')}; //复制中队下面的所有中队
                // this.squadrons.forEach(v=>{
                //     postBody.push({deptId:this.searchParams.deptId, middeptId:v.value,times:times})
                // })
                copyPostDeploy(postBody).then(res => {
                    if (res.isSuccess) {
                        this.copyPostModalVisible = false;
                        this.$message.success({content: '复制岗位成功!', key: 'loading1'});
                        this.getEmergencyDutySurveyList(); //刷新部署列表
                    } else {
                        this.$message.error({content: res.info ? res.info : '复制岗位失败!', key: 'loading1'});
                    }
                }, (e) => {
                    this.$message.error({content: e.message ? e.message : '复制岗位失败!', key: 'loading1'});
                })

            },
            checkDetail(item) { //查看详情
                // this.crudModalTitle = "岗位查看";
                this.$message.loading({content: '详情请求中!', key: 'loading1', duration: 0});
                getPositionDetail(item.id).then(res => {
                    if (res.isSuccess) {
                        this.$message.success({content: '详情请求成功!', key: 'loading1'});
                        this.postInforInMap = res.data;
                        if (this.postInforInMap.type == 2) {
                            this.postInforInMap.name = this.postInforInMap.name.split(",")[0];
                        }
                        this.postDetailModalVisible = true;
                    } else {
                        this.$message.success({content: res.info ? res.info : '详情请求成功!', key: 'loading1'});
                    }
                })

            },
            postDetailClose() { //关闭详情
                this.postDetailModalVisible = false;
                this.postInforInMap = {};
            },
            editItem(item) { //编辑
                //      mileage: 0,
                //     positionType: 1,
                //     deptId: "",
                //     startTime: "",
                //     endTime: "",
                //     takes: [
                //     {
                //         motorwayId: '',//道路id
                //         startStake: '',//开始桩号
                //         endStake: '',//结束桩号
                //         mileage: ''//距离
                //     }
                // ]
                this.crudModalTitle = "编辑岗位";
                getPositionDetail(item.id).then(res => {
                    if (res.isSuccess) {
                        const itemData = res.data
                        this.getbrigadeList(); //大队
                        this.requestBody = defaultRequestBody();

                        // console.log(11111);
                        // console.log(item);

                        this.requestBody.deptId = itemData.deptId;
                        this.requestBody.middeptId = itemData.middeptId;
                        this.requestBody.name = itemData.name;
                        this.requestBody.positionType = itemData.type*1;
                        this.requestBody.id = itemData.id;
                        this.requestBody.startTime = moment(itemData.startTime).format("HH:mm");
                        this.requestBody.endTime = moment(itemData.endTime).format("HH:mm");

                        // console.log(this.requestBody)

                        this.requestBody.takes = itemData.lstTake;
                        this.requestBody.takes.forEach(v => {
                            v.startStake = v.startStake * 1;
                            v.endStake = v.endStake * 1;
                            v.mileage = v.mileage * 1;
                            this.requestBody.mileage = this.requestBody.mileage + v.mileage;
                        })
                        if (this.requestBody.positionType == 2) {
                            const n = this.requestBody.name.split(',');
                            this.requestBody.lawEnforcement = n[1];
                            this.getLawEnforcementStation();  // 获取执法站
                        }
                        this.positionTypeChange();
                        // console.log(this.requestBody);

                        this.crudModalVisible = true;
                    }
                })

            },
            editVisibleChange(item) {
                if (!item.EV) {
                    const loadingObj = this.$message.loading({
                        content: '正在查询此岗位是否部署警察！...',
                        key: 'loading1',
                        duration: 0
                    });
                    const tempData = {
                        id:item.id,
                        nlevel:3,
                        deptId:this.searchParams.deptId
                    }
                    getIsDeploy(tempData).then(res => {
                        if (res.isSuccess) {
                            loadingObj();
                            if (res.data) {
                                item.EV = true
                            } else {
                                this.editItem(item)
                            }
                        } else {
                            this.$message.error({
                                content: res.info ? res.info : '查询失败！',
                                key: 'loading1',
                                duration: 2
                            });

                        }
                    })
                } else {
                    item.EV = false;
                }

            },
            deleteVisibleChange(item) {
                console.log(item)
                if (!item.DV) {
                    const loadingObj = this.$message.loading({
                        content: '正在查询此岗位是否部署警察！...',
                        key: 'loading1',
                        duration: 0
                    });
                    const tempData = {
                        id:item.id,
                        nlevel:3,
                        deptId:this.searchParams.deptId
                    }
                    getIsDeploy(tempData).then(res => {
                        if (res.isSuccess) {
                            item.DV = true
                            loadingObj();
                            if (res.data) {
                                item.DT = "会清除当前岗位下的警察部署！确认删除?"
                            } else {
                                item.DT = "确认删除?"
                            }
                        } else {
                            this.$message.error({
                                content: res.info ? res.info : '查询失败！',
                                key: 'loading1',
                                duration: 2
                            });
                            item.DV = true
                            item.DT = "确认删除?"
                        }
                        this.$forceUpdate();
                    })
                } else {
                    item.DV = false;
                }

            },
            deleteItem(item) { //删除岗位详情
                this.$message.loading({content: '岗位部署详情删除中...', key: 'loading1', duration: 0});
                deletePosition(item.id).then(res => {
                    if (res.isSuccess) {
                        this.$message.success({content: '岗位部署详情删除成功!', key: 'loading1', duration: 2});
                        this.getEmergencyDutySurveyList();
                        this.getEmergencyDutyList();
                    } else {
                        this.$message.error({
                            content: res.info ? res.info : '岗位部署详情删除失败!',
                            key: 'loading1',
                            duration: 2
                        });
                    }
                })
            },
            getbrigadeList() {  //大队
                getbrigadeList().then(res => {
                    if (res.isSuccess) {
                        this.brigadeList = res.data
                        this.brigadeChange(false);
                    }
                });
            },
            positionTypeChange() {
                if (this.requestBody.positionType == 1) {
                    this.rules.name[0].required = true;
                    this.rules.lawEnforcement[0].required = false;
                } else {
                    this.rules.name[0].required = false;
                    this.rules.lawEnforcement[0].required = true;
                }
                this.$forceUpdate()
            },
            brigadeChange(changeFlag = true) { //大队变更
                this.getsquadronList();
                this.getexpresswayList(); //获取高速
                this.getLawEnforcementStation();  // 获取执法站

                if(changeFlag){
                    this.requestBody.middeptId = "";  //中队
                    this.requestBody.lawEnforcement = ""; //执法站
                    this.requestBody.takes =  [  //任务
                        {
                            id: "",
                            motorwayId: '',//道路id
                            startStake: '',//开始桩号
                            endStake: '',//结束桩号
                            min: 0,//开始桩号
                            max: 0,//结束桩号
                            mileage: '',//距离
                            range: "",
                        }
                    ];
                }



            },

            //中队变更
            middeptIdChange() {

            },

            getsquadronList() {  //中队
                // console.log(this.brigade);
                getsquadronList({deptId: this.requestBody.deptId}).then(res => {
                    if (res.isSuccess) {
                        this.squadronList = res.data
                    }
                });
            },
            getexpresswayList() {  //高速
                const reqBody = {
                    deptId: this.requestBody.deptId,
                    // middeptId: this.requestBody.middeptId,
                    nlevel: 3
                }
                getexpresswayList(reqBody).then(res => {
                    if (res.isSuccess) {
                        this.expresswayList = res.data;
                    }
                })
            },
            getLawEnforcementStation() {  //获取执法站
                console.log("获取执法站")
                getLawEnforcementStation({
                    deptId: this.requestBody.deptId,
                    // middeptId: this.requestBody.middeptId,
                    nlevel: 3
                }).then(res => {
                    if (res.isSuccess) {
                        this.lawEnforcementStation = res.data;
                    }
                })
            },
            getLawRadius() {  //获取执法站半径
                console.log("获取执法站半径")
                getLawRadius().then(res => {
                    console.log(res)
                    if (res.isSuccess) {
                        this.lawRadius = res.data;
                    }
                })
            },
            addTakes(i) {  //添加任务
                this.requestBody.takes.splice(i + 1, 0, {
                    motorwayId: '',//道路id
                    startStake: '',//开始桩号
                    endStake: '',//结束桩号
                    mileage: ''//距离
                })
            },
            minusTakes(i) {  //删除任务
                this.requestBody.takes.splice(i, 1)
            },
            selectRange(item) {
                var selectWay = this.expresswayList.find((v) => {
                    return v.value == item.motorwayId;
                })
                if (!selectWay) {
                    selectWay = {}
                }
                this.$refs.deploymentMap.selectRange(item, selectWay, (range) => {
                    item.range = range
                    this.$forceUpdate();
                })

            },
            onSubmit() { //布岗保存
                this.$refs.ruleForm.validate(valid => {
                    // console.log('this.requestBody');
                    // console.log(this.requestBody);
                    if (valid) {
                        const requestBody =JSON.parse(JSON.stringify(this.requestBody))

                            requestBody.startTime = moment(this.selectedRow.positiondate).format('YYYY-MM-DD') + " " + requestBody.startTime;
                        if(requestBody.endTime == "00:00"){  //结束时间零点为第二天零点
                            requestBody.endTime = moment(this.selectedRow.positiondate).format('YYYY-MM-DD') + " " + "23:59:59";
                        }else{
                            requestBody.endTime = moment(this.selectedRow.positiondate).format('YYYY-MM-DD') + " " + requestBody.endTime;
                        }
                        if (moment(requestBody.startTime).isAfter(requestBody.endTime)) {
                            this.$message.error("岗位开始时间须早于结束时间！")
                            return;
                        }

                        let flag = false;
                        this.emergencyDutyList.forEach((v) => {
                            if (v.deptId == requestBody.deptid && v.middeptid == requestBody.middeptId) {
                                let tempStart;
                                let tempEnd;

                                tempStart = v.currenttime + " " + v.starttime

                                if(v.endtime == "00:00"){
                                    tempEnd =  v.currenttime + " " + "23:59:59"
                                }else{
                                    tempEnd = v.currenttime + " " + v.endtime
                                }
                                if (requestBody.positionType == 1) {
                                    if (requestBody.name == v.name&&requestBody.id!=v.id) {
                                        if (moment(requestBody.endTime).isAfter(tempStart) || moment(requestBody.starttime).isBefore(tempEnd)) {
                                            flag = true
                                        }
                                        if(requestBody.endTime == tempStart||requestBody.starttime == tempEnd){
                                            flag = false
                                        }
                                    }
                                } else if (requestBody.positionType == 2) {
                                    if (requestBody.lawEnforcement == v.id2&&requestBody.id != v.id) {
                                        if (moment(requestBody.endTime).isAfter(tempStart) || moment(requestBody.starttime).isBefore(tempEnd)) {
                                            flag = true
                                        }
                                        if(requestBody.endTime == tempStart||requestBody.starttime == tempEnd){
                                            flag = false
                                        }
                                    }
                                }
                            }
                        })
                        if (flag) {
                            this.$message.error("同一个岗位名称，不能出现在重叠的时间！")
                            return;
                        }

                        if (requestBody.positionType == 2) { //极直岗位
                            // console.log(requestBody.lawEnforcement)
                            const seletedpost = this.lawEnforcementStation.find((v) => {
                                return v.id == requestBody.lawEnforcement;
                            })
                            // console.log(1111)
                            requestBody.name = seletedpost.name + ',' + seletedpost.id;
                            // console.log(this.$refs.deploymentMap.mapApp.changeMeterToDegree)
                            // console.log(seletedpost.range, this.lawRadius)
                            const rad = this.$refs.deploymentMap.mapApp.changeMeterToDegree(seletedpost.coordinate, this.lawRadius);//米转度
                            seletedpost.range = seletedpost.coordinate + "," + rad;
                            requestBody.takes = [seletedpost]
                        }

                        this.$message.loading({content: '数据提交中...', key: 'loading1', duration: 0});

                        console.log(requestBody)
                        if (requestBody.id) {
                            updatePostion(requestBody).then(res => { //修改
                                if (res.isSuccess) {
                                    this.crudModalVisible = false;
                                    this.getEmergencyDutySurveyList()
                                    this.getEmergencyDutyList()
                                    this.$message.success({content: '编辑布岗成功!', key: 'loading1', duration: 2});
                                } else {
                                    this.$message.error({
                                        content: res.info ? res.info : '编辑布岗失败!',
                                        key: 'loading1',
                                        duration: 2
                                    });
                                }
                            })
                        } else {
                            addPosition(requestBody).then(res => {  //添加
                                if (res.isSuccess) {
                                    // this.selectedRow.substatus = 1;//已部署
                                    this.crudModalVisible = false;
                                    this.getEmergencyDutyList();
                                    this.$message.success({content: '布岗成功!', key: 'loading1', duration: 2});
                                } else {
                                    this.$message.error({
                                        content: res.info ? res.info : '布岗失败!',
                                        key: 'loading1',
                                        duration: 2
                                    });
                                }
                            })
                        }

                    }
                });
            },
            canDeploy(){
                if (this.selectedRow.substatus == 2) {
                    if (moment().isBefore(this.selectedRow.positiondate)) {
                        return true
                    } else {
                        return false;
                    }

                } else {
                    return true
                }
            },
            canEdit(record) {
                if (this.selectedRow.substatus == 2) {
                    if (moment().isBefore(record.currenttime + " " + record.starttime)) {
                        return true
                    } else {
                        return false;
                    }

                } else {
                    return true
                }
            },
            exportExcel(deptName) {
                // jsonToExcel(this.emergencyDutyList, "布岗"); //导出
                this.$message.loading({content: '数据加载中...', key: 'dutyLoadingKey', duration: 0});
                exportEmergencyDutyList(this.searchParams).then(res => {
                    if (res.isSuccess) {

                        this.$message.success({content: '加载成功!', key: 'dutyLoadingKey', duration: 2});
                        res.data.forEach(v => {
                            if (v.positiontype == 2) {
                                const n = v.name.split(',');
                                v.name = n[0];
                                v.id2 = n[1];
                            }
                            v.fullName = v.middeptname + "-" + v.name;
                        })

                        var styleBase = {
                            border: { // 设置边框
                                top: { style: 'thin' },
                                bottom: { style: 'thin' },
                                left: { style: 'thin' },
                                right: { style: 'thin' }
                            }
                        };
                        const outPut = {
                            A1:{v:"序号",s:styleBase},
                            B1:{v:"日期",s:styleBase},
                            C1:{v:"岗位类型",s:styleBase},
                            D1:{v:"岗位名称",s:styleBase},
                            E1:{v:"所属部门",s:styleBase},
                            F1:{v:"岗位范围",s:styleBase},
                            G1:{v:"岗位时段",s:styleBase},
                        };
                        res.data.forEach((v,i)=>{
                                outPut['A'+(i+2)]={v:i+1,s:styleBase};
                                outPut['B'+(i+2)]={v:v.currenttime,s:styleBase};
                                outPut['C'+(i+2)]={v:getDictByTypeValue('dutyType',v.positiontype).label,s:styleBase};
                                outPut['D'+(i+2)]={v:v.fullName,s:styleBase};
                                outPut['E'+(i+2)]={v:v.middeptname,s:styleBase};
                                outPut['F'+(i+2)]={v:(v.dutyRange2?(v.position + '-' + v.dutyRange2):v.position),s:styleBase};
                                outPut['G'+(i+2)]={v:v.starttime+"-"+v.endtime,s:styleBase};
                        })
                        //json转sheet
                    outPut['!cols']= [
                            {wch: 10},
                            {wch: 15},
                            {wch: 15},
                            {wch: 40},
                            {wch: 20},
                            {wch: 20},
                            {wch: 15}
                        ];
                    outPut['!ref'] =  'A1:G'+res.data.length+1;

                        var wb = {
                            SheetNames: ['Sheet1'],
                            Sheets: {
                                // Sheet1 表示工作簿名称
                                Sheet1: outPut
                            }
                        };

                    // XLSX.writeFile(wb,deptName+"部岗详情.xlsx");

                        var tmpDown = new Blob([
                            s2ab(
                                // 这里的数据是用来定义导出的格式类型
                                XLSX.write(wb, {
                                    bookType: 'xlsx',
                                    bookSST: false,
                                    type: 'binary'
                                })
                            )
                        ], {
                            type: ""
                        });
                        saveAs(tmpDown,deptName+"部岗详情.xlsx");

                    } else {
                        this.$message.error({
                            content: res.info ? res.info : '加载失败!',
                            key: 'dutyLoadingKey',
                            duration: 2
                        });
                    }
                }, (e) => {
                    this.$message.error({
                        content: e.message ? e.message : '加载失败!',
                        key: 'dutyLoadingKey',
                        duration: 2
                    });
                })
            }

        }, mounted() {
            // this.getEmergencyDutySurveyList();
            // this.getEmergencyDutyList();
            this.getLawRadius(); //获取执法站半径


        }, beforeRouteEnter(to, from, next) {
            console.log('beforeRouteEnter ---- ');
            if (!store.state.isLogin) {
                login().then((res) => {
                    if (res.isSuccess) {
                        store.commit("setLoginInfor", res.data);
                        next()
                    } else {
                        // alert("获取用户信息失败");
                        next()
                    }
                }).catch((e) => {
                    // alert("获取用户信息失败")
                    next();
                })
            } else {
                next()
            }
        },
    };

    function defaultRequestBody() {
        return {
            mileage: 0,
            positionType: 1,
            deptId: "",
            middeptId: "",
            lawEnforcement: "",
            name: "",
            startTime: "09:00",
            endTime: "00:00",
            takes: [
                {
                    id: "",
                    motorwayId: '',//道路id
                    startStake: '',//开始桩号
                    endStake: '',//结束桩号
                    min: 0,//开始桩号
                    max: 0,//结束桩号
                    mileage: '',//距离
                    range: "",
                }
            ]
        }
    }
</script>

<style scoped>
    >>> .ant-table-small {
        border: none;
    }

    >>> .rowActive {
        background: #ccecff
    }

    >>> .cursorPionter {
        cursor: pointer;
    }

    >>> .ant-form-item {
        margin-bottom: 0;
    }

    >>> .ant-form-item-control {
        line-height: 30px;
    }

    >>> .ant-form-item-label {
        line-height: 30px;

    }

    >>> .ant-input-group-addon {
        padding: 0 4px
    }

    >>> .ant-input-group-wrapper {
        top: 0 !important;
    }
</style>
